//
//  YJNetMonitor.m
//  Cszy
//
//  Created by SC on 16/11/30.
//  Copyright © 2016年 SC. All rights reserved.
//

#import "YJNetMonitor.h"

@implementation YJNetMonitor


// 实例化单例对象
+ (YJNetMonitor *)shareMonitorNetWorkState
{
    static YJNetMonitor *shareObj = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareObj = [[YJNetMonitor alloc] init];
        [shareObj addMonitorNetWorkState];
        shareObj.startNetType = [shareObj getCurrentNetWorkType];

    });
    
    return shareObj;
}

// 获取当前网络类型
- (NSInteger)getCurrentNetWorkType
{
    NSInteger netWorkType = NotReachable;
    
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    switch (reach.currentReachabilityStatus)
    {
        case NotReachable:
            //无连接
            netWorkType = NotReachable;
            break;
            
        case ReachableViaWiFi:
            //WiFi
            netWorkType = ReachableViaWiFi;
            break;
        case ReachableViaWWAN:
            //有网络
            netWorkType = ReachableViaWWAN;
            break;
        case kReachableVia2G:
            //2G
            netWorkType = kReachableVia2G;
            break;
            
        case kReachableVia3G:
            //3G
            netWorkType = kReachableVia3G;
            break;
            
        case kReachableVia4G:
            //4G
            netWorkType = kReachableVia4G;
            break;
            
        default:
            //无连接
            netWorkType = NotReachable;
            break;
    }
    return netWorkType;

}

// 添加网络监听
- (void)addMonitorNetWorkState
{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netWorkStateChange) name:kReachabilityChangedNotification object:nil];
    self.conn = [Reachability reachabilityForInternetConnection];
    //self.conn = [Reachability reachabilityWithHostName:@"https://www.baidu.com/"];
    [self.conn startNotifier];
}

- (void)netWorkStateChange
{
    if ([_delegate respondsToSelector:@selector(netWorkStateChanged)]) {
        
        [self.delegate netWorkStateChanged];
    }

}

/**
 * 获取网络状态
 * YES 有网络
 * NO  无网络
 */
- (BOOL)getNetWorkState
{
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    
    if ([wifi currentReachabilityStatus] != NotReachable) {
        
        return YES;
    }else if([conn currentReachabilityStatus] != NotReachable) {
        
        return YES;
    }else{
        
        return NO;
    }
}

@end
